<template>
	<view>
		<view class="navbar copy" :style="{opacity: 1-opacity}">
			<view :style="{height: `${statusBar}px`}">
				
			</view>
			<view class="u-flex u-row-between" :style="{height: `${navBar-statusBar}px`}">
				<navigator open-type="navigateBack">
					<text class="iconfont icon-goback u-font-32"></text>
				</navigator>
				<view>
					<text v-if="id==userInfo.userId" class="iconfont icon-camera u-font-44"></text>
					<text class="u-p-x-16" v-else></text>
				</view>
			</view>
			<view class="infilling"></view>
		</view>
		<view class="navbar origin" :style="{opacity: opacity}">
			<view :style="{height: `${statusBar}px`}">
				
			</view>
			<view class="u-flex u-row-between" :style="{height: `${navBar-statusBar}px`}">
				<navigator open-type="navigateBack">
					<text class="iconfont icon-goback u-font-32"></text>
				</navigator>
				<view class="">
					<text class="u-font-32">朋友圈</text>
				</view>
				<view>
					<text v-if="id==userInfo.userId" class="iconfont icon-camera u-font-44" @tap="jumpTo('/pages/moment/publish')"></text>
					<text class="u-p-x-16" v-else></text>
				</view>
			</view>
		</view>
		<view class="head" :class="{unfold:unfold}" @tap="unfold=!unfold" :style="{backgroundImage: `url(${bgImg}),url('/static/images/momentBg.jpg')`}">
			<view class="gradual-box">
				<view class="menu-box" v-if="id==userInfo.userId">
					<view class="item text-white" @tap.stop="changeBgImg">
						 <text class="iconfont icon-tupian u-font-46"></text>
						 <text class="u-font-22">换封面</text>
					</view>
				</view>
				<view class="user-box" @tap.stop>
					<view class="name">
						<text>{{info.userName}}</text>
					</view>
					<view class="avatar" :style="{backgroundImage: `url(${info.avatarUrl}),url('https://s1.ax1x.com/2023/03/19/ppY2oq0.jpg')`}">
						
					</view>
				</view>
			</view>
		</view>
		<view style="height: 200rpx;padding-top: 70rpx;">
			<view v-if="info.profiles" class="u-text-right u-p-x-30 u-font-26 text-gray">
				{{info.profiles}}
			</view>
		</view>
		<view v-for="(item,idx) in moments.list" :key="idx" class="u-p-x-30 u-p-y-20 u-border-bottom">
			<note :info="item" 
			@praise="onPraise(item)" 
			@comment="onComment(item,$event)"
			@moreComment="moreComment(item)"
			@remove="removeMoment(item)"
			></note>
		</view>
		<view class="empty" v-if="moments.nomore&&!moments.list.length">
			<text >这里空空如也</text>
		</view>
		<view class="send-wrap" :class="{show:input.show}">
			<view class="send-mask" @touchmove.stop.prevent @tap="closeInput">
				
			</view>
			<view class="send-bar">
				<view class="input">
					<textarea
					 class="textarea"
					 :focus="input.focus"
					 :show-confirm-bar="false"
					 cursor-spacing="16"
					 :auto-height="true"
					 v-model="input.value" 
					 :placeholder="input.at?`回复${input.at.userName}:`:'评论'" 
					 placeholder-class="placeholder"
					></textarea>
				</view>
				<view class="icon-item" @tap="emoji.show=!emoji.show">
					<text class="cuIcon-emoji"></text>
				</view>
				<view class="send-btn" :class="{disabled:!input.value.trim()}" @tap="send">
					<text>发送</text>
				</view>
			</view>
			<scroll-view v-show="emoji.show" class="emoji-box" scroll-y>
				<view class="emoji-grid">
					<view class="emoji" v-for="(item,idx) in emoticon" :key="idx">
						<image class="emoji-img" :src="item.url" mode="aspectFit"></image>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<u-modal
			v-model="ask.show" 
			:content="ask.content" 
			:title="ask.title" 
			:show-title="!!ask.title"
			:cancelText="ask.cancelTxt" 
			:confirm-text="ask.confirmTxt" 
			show-cancel-button
			@cancel="reject"
			@confirm="resolve"
		/>
		<u-action-sheet 
		:list="sheet.list" 
		v-model="sheet.show" 
		border-radius="20" 
		safe-area-inset-bottom 
		@click="resolve" 
		@close="reject"/>
	</view>
</template>

<script>
	import {jumpTo,toast} from "@/utils/util.js"
	import * as fileUtil from "@/utils/file.js"
	import note from "./note.vue"
	import {
		emojiMap,
		emojiName,
		emojiUrl
	} from '@/utils/emojiMap.js'
	import {setMyBgImg,refreshUserInfo,getPortalUserInfo} from "@/api/user.js"
	import {getFriendMomentsByUser,remove as removeMoment} from "@/api/dynamic.js"
	import {genres,praise} from "@/api/praise.js"
	import * as commentAPI from "@/api/comment.js"
	import {mapGetters,mapActions} from "vuex"
	let bridge = null
	export default {
		components:{
			note
		},
		data() {
			return {
				id:'',
				info:{},
				scrollTop:0,
				unfold:false,
				input:{
					show:false, 
					focus:false,
					value:'', 
					cache:{}, 
					note:null, 
					at:null 
				},
				emoticon:emojiName.map((item)=>({text:item,url:`${emojiUrl}${emojiMap[item]}`})),
				emoji:{
					show:false
				},
				moments:{ 
					list:[],
					pageNo:1,
					pageSize:10,
					nomore:false,
					loading:false
				},
				ask:{ 
					show:false,
					content:'',
					title:'',
					confirmTxt:'',
					cancelTxt:''
				},
				sheet:{
					show:false,
					list:[]
				},
			};
		},
		computed:{
			...mapGetters('user',['userInfo']),
			bgImg(){
				return this.info&&this.info.bgImg
			},
			opacity(){
				return Math.min(this.scrollTop/(uni.upx2px(560)-this.navBar),1) 
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop
		},
		onLoad({id}){
			this.id = id
			this.initInfo()
			this.resetMoment()
			if(this.id==this.userInfo.userId){
				uni.$on('moment_published',this.resetMoment)
			}
		},
		onUnload() {
			if(this.id==this.userInfo.userId){
				uni.$off('moment_published',this.resetMoment)
			}
		},
		onReachBottom() {
			this.moreMoment()
		},
		methods:{
			jumpTo,
			resolve(e){
				bridge&&bridge.resolve&&bridge.resolve(e)
			},
			reject(e){
				bridge&&bridge.reject&&bridge.reject(e)
			},
			...mapActions('user',['fetchUserInfo']),
			async initInfo(){
				this.info = await getPortalUserInfo(this.id)
			},
			async resetMoment(){
				this.moments.list = []
				this.moments.pageNo = 1
				this.moments.nomore = false
				await this.moreMoment()
			},
			async moreMoment(){
				if(this.moments.loading){
					throw new Error('正在请求中')
				}
				try{
					this.moments.loading = true
					if(this.moments.nomore){
						return []
					}
					const list = await getFriendMomentsByUser({...this.moments,id:this.id})
					if(!list||list.length<this.moments.pageSize){
						this.moments.nomore = true
					}else{
						this.moments.pageNo ++
					}
					this.moments.list.push(...list.map(item=>({...item,nomore:item.commentList.length<5,pageNo:2})))
				}catch(e){
					console.log(e)
				}finally{
					this.moments.loading = false
				}
			},
			async removeMoment(note){ 
				await new Promise((resolve,reject)=>{
					bridge = {
						resolve,
						reject
					}
					this.ask.show = true
					this.ask.title = '提示'
					this.ask.content = '删除该朋友圈?'
					this.ask.confirmTxt = '确定'
					this.ask.cancelTxt = '取消'
				})
				if(this.removeMoment.lock){
					throw new Error('正在请求中')
				}
				try{
					this.removeMoment.lock = true
					await removeMoment(note.dynamicId)
					this.moments.list = this.moments.list.filter(({dynamicId})=>dynamicId!=note.dynamicId)
				}finally{
					this.removeMoment.lock = false
				}
			},
			async changeBgImg(){
				try{
					let file = await new Promise((resolve,reject)=>{
						uni.$once("uAvatarCropper",resolve)
						jumpTo("/uview-ui/components/u-avatar-cropper/u-avatar-cropper?destWidth=600&destHeight=500&rectWidth=300&rectHeight=250&fileType=jpg")
					})
					const path = await fileUtil.uploadFile({
						pre:'head/',
						file: file
					})
					await setMyBgImg(path)
					this.info.bgImg = path
					refreshUserInfo().then(()=>{
						this.fetchUserInfo()
					})
				}catch(e){
					console.log(e)
					toast(e.message||'设置失败,请稍后重试')
				}
			},
			async onPraise(note){
				if(note.isPraise=='1'){
					await praise({id:note.dynamicId,genre:genres.dynamic,type:2})
					note.praiseList = note.praiseList.filter(({userId})=>userId!=this.userInfo.userId)
					note.isPraise = '0'
				}else{
					await praise({id:note.dynamicId,genre:genres.dynamic,type:1})
					note.praiseList.push({
						approve:this.userInfo.approve,
						avatarUrl:this.userInfo.avatarUrl,
						createDate:new Date().Format('yyyy-MM-dd HH:mm:ss'),
						level:this.userInfo.level,
						profiles:this.userInfo.profiles,
						sex:this.userInfo.sex,
						userId:this.userInfo.userId,
						userName:this.userInfo.userName
					})
					note.isPraise = '1'
				}
			},
			onComment(note,comment){
				if(!!comment&&comment.userId==this.userInfo.userId){
					this.commentSheet(note,comment)
				}else{
					this.openInput(note,comment)
				}
			},
			openInput(note,comment){
				this.input.note = note
				this.input.at = comment
				const key = comment?comment.commentId:note.dynamicId
				if(this.input.cache[key]){
					this.input.value = this.input.cache[key]
				}
				this.input.show = true
				this.input.focus = true
			},
			closeInput(){
				const key = this.input.at?this.input.at.commentId:this.input.note.dynamicId
				this.input.cache[key] = this.input.value
				this.input.value = ''
				this.input.show = false
				this.input.focus = false
				this.emoji.show = false
			},
			async send(){ 
				if(this.send.lock){
					throw new Error('正在请求中')
				}
				if(!this.input.value.trim()){
					return
				}
				try{
					this.send.lock = true
					const note = this.input.note
					const at = this.input.at
					if(this.input.at){
						await this.addReply()
					}else{
						await this.addComment()
					}
					const key = this.input.at?this.input.at.commentId:note.dynamicId
					this.input.value = ''
					this.closeInput()
				}finally{
					this.send.lock = false
				}
			},
			async addReply(){ 
				const note = this.input.note
				const at = this.input.at
				const res =  await commentAPI.addReply({
					id:note.dynamicId,
					genre:genres.dynamic,
					content:this.input.value,
					pid:at.commentId
				})
				note.commentList.push({
					avatarUrl:this.userInfo.avatarUrl,
					businessId:res.businessId,
					businessType:res.businessType,
					commentCount:0,
					commentId:res.commentId,
					commentReplyRespList:[],
					content:res.content,
					createDate:new Date().Format('yyyy-MM-dd HH:mm:ss'),
					createRegion:res.createRegion,
					ext:res.ext,
					like:false,
					parentId:at.commentId,
					parentUserName:at.userName,
					praiseCount:0,
					replyCount:0,
					userId:this.userInfo.userId,
					userName:this.userInfo.userName
				})
			},
			async addComment(){ 
				const note = this.input.note
				
				const res = await commentAPI.add({
					id:note.dynamicId,
					genre:genres.dynamic,
					content:this.input.value,
				})
				note.commentList.push({
					avatarUrl:this.userInfo.avatarUrl,
					businessId:res.businessId,
					businessType:res.businessType,
					commentCount:0,
					commentId:res.commentId,
					commentReplyRespList:[],
					content:res.content,
					createDate:new Date().Format('yyyy-MM-dd HH:mm:ss'),
					createRegion:res.createRegion,
					ext:res.ext,
					like:false,
					parentId:'',
					parentUserName:'',
					praiseCount:0,
					replyCount:0,
					userId:this.userInfo.userId,
					userName:this.userInfo.userName
				})
			},
			async moreComment(note){
				if(this.moreComment.lock){
					throw new Error('正在请求中')
				}
				try{
					this.moreComment.lock = true
					if(note.nomore){
						return []
					}
					const list = await commentAPI.getList({id:note.dynamicId,genre:genres.dynamic,pageNo:note.pageNo})
					if(!list||list.length<5){
						note.nomore = true
					}else[
						note.pageNo++
					]
					note.commentList.push(...list)
				}finally{
					this.moreComment.lock = false
				}
			},
			async removeComment(note,comment){
				await commentAPI.remove(comment.commentId)
				note.commentList = note.commentList.filter(({commentId})=>commentId!=comment.commentId)
			},
			async commentSheet(note,comment){
				const opt = await new Promise((resolve, reject)=>{
					const list = [{text:'删除',fun:'removeComment'}]
					this.sheet.show=true
					this.sheet.list = list
					bridge = {
						resolve:(idx)=>{
							resolve(list[idx])
						},
						reject
					}
				})
				if(opt.fun=='removeComment'){
					this.removeComment(note,comment)
				}
			}
		
		}
	}
</script>

<style>
	page{
		background-color: #ffffff;
		color: #000000;
	}
</style>

<style lang="scss" scoped>
	.navbar{
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		padding: 0 30rpx;
		&.copy{
			background-image: linear-gradient(rgba($color:#666666,$alpha:0.3),rgba($color:#666666,$alpha:0));
			color: #ffffff;
			pointer-events: none;
			.infilling{
				height: 90rpx;
			}
		}
		&.origin{
			background-color: #eeeeee;
		}
	}
	.head{
		height: 560rpx;
		background-size: cover;
		background-position: center;
		transition: all 300ms ease-out;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		&.unfold{
			height: 1000rpx;
			.menu-box{
				opacity: 1;
				pointer-events: auto;
			}
			.user-box{
				opacity: 0;
				pointer-events: none;
			}
		}
		.gradual-box{
			background-image: linear-gradient(rgba($color:#333333,$alpha:0),rgba($color:#333333,$alpha:0.5));
			height: 200rpx;
			position: relative;
		}
		.menu-box{
			position: absolute;
			right: 0rpx;
			bottom: 0rpx;
			padding: 30rpx;
			opacity: 0;
			pointer-events: none;
			transition: all 300ms ease-out;
			.item{
				display: flex;
				flex-direction: column;
				align-items: center;
			}
		}
		.user-box{
			position: absolute;
			left: 0;
			right: 0rpx;
			bottom: 0rpx;
			padding: 20rpx 30rpx;
			display: flex;
			justify-content: flex-end;
			align-items: flex-end;
			opacity: 1;
			pointer-events: auto;
			transition: all 300ms ease-out;
			.name{
				color: #ffffff;
				font-size: 36rpx;
				font-weight: bold;
				line-height: 40rpx;
			}
			.avatar{
				width: 140rpx;
				height: 140rpx;
				border-radius: 14rpx;
				margin-left: 20rpx;
				margin-bottom: -80rpx;
				background-position: center;
				background-size: cover;
			}
		}
	}
	.send-wrap{
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
		z-index: 10;
		transform: translateY(200%);
		&.show{
			transform: translateY(0%);
		}
		.send-mask{
			flex: 1;
			
		}
		.send-bar{
			display: flex;
			align-items: flex-end;
			background-color: #ffffff;
			padding: 20rpx 30rpx;
			.input{
				padding: 10rpx 20rpx;
				display: flex;
				align-items: center;
				background-color: #F5F6F7;
				max-height: 200rpx;
				overflow: auto;
				border-radius: 10rpx;
				flex: 1;
			}
			.textarea{
				line-height: 40rpx;
				font: 32rpx;
				width: 100%;
			}
			.placeholder{
				line-height: 40rpx;
				font: 32rpx;
				color: #999999;
			}
			.icon-item{
				line-height: 60rpx;
				font-size: 48rpx;
				margin-left: 20rpx;
			}
			.send-btn{
				height: 60rpx;
				line-height: 60rpx;
				margin-left: 20rpx;
				background-color: #39b54a;
				color: #ffffff;
				padding: 0 30rpx;
				border-radius: 10rpx;
				border: 2rpx solid #39b54a;
				&.disabled{
					border-color: #999999;
					color: #999999;
					background-color: transparent;
					pointer-events: none;
				}
			}
		}
		.emoji-box{
			height: 400rpx;
			background-color: #eeeeee;
		}
		.emoji-grid{
			display: grid;
			grid-template-columns: repeat(8,1fr);
			padding: 20rpx 10rpx;
			.emoji{
				margin: 10rpx 0;
				display: flex;
				justify-content: center;
			}
			.emoji-img{
				width: 60rpx;
				height: 60rpx;
			}
		}
	}
	.empty{
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 50rpx 30rpx;
		color: #999999;
		font-size: 36rpx;
		&::before{
			content: '';
			width: 80rpx;
			height: 1rpx;
			background-color: #999999;
			margin-right: 10rpx;
		}
		&::after{
			content: '';
			width: 80rpx;
			height: 1rpx;
			background-color: #999999;
			margin-left: 10rpx;
		}
	}
</style>
